package main

import (
	"sync"
)

// Singleton 结构体
type Singleton struct {
	Instance *Singleton
	Data     string
}

var instance *Singleton
var once sync.Once

// GetInstance 获取单例实例
func GetInstance() *Singleton {
	once.Do(func() {
		instance = &Singleton{
			Data: "This is a singleton instance.",
		}
	})
	return instance
}

func main() {
	// 获取单例实例
	inst1 := GetInstance()
	inst2 := GetInstance()

	// 验证单例模式
	if inst1 != inst2 {
		panic("Singleton instances are not the same")
	}
	println(inst1.Data)

	// 测试并发环境
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			inst := GetInstance()
			if inst != inst1 {
				panic("Singleton instances are not the same in concurrent environment")
			}
		}()
	}
	wg.Wait()
}
